<?php

/* 退款 */

class RefundModel extends BaseModel {

    var $table = 'refund';
    var $prikey = 'refund_id';
    var $_name = 'refund';
    var $_relation = array(
        'belongs_to_order' => array(
            'model' => 'order',
            'type' => BELONGS_TO,
            'foreign_key' => 'order_id',
            'reverse' => 'has_refund',
        ),
    );

    function gen_refund_sn() {

        mt_srand((double) microtime() * 1000000);
        $timestamp = gmtime();
        $y = date('Y', $timestamp);
        $z = date('z', $timestamp);
        $refund_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        $refund = parent::get(array('conditions' => 'refund_sn=' . $refund_sn, 'fields' => 'refund_id'));
        if (!$refund) {

            return $refund_sn;
        }


        return $this->_gen_refund_sn();
    }

    function get_order_can_confirm_goods($order_info, $adjust_rate = 1) {

        $goods_close_refund_and_no_refund = array();
        $ordergoods_mod = &m('ordergoods');
        $goods_amount = $shipping_fee = 0;

        $ordergoods = $ordergoods_mod->find(array('conditions' => "order_id=" . $order_info['order_id']));
        foreach ($ordergoods as $key => $goods) {
            $goods_refund = parent::get(array('conditions' => "order_id=" . $order_info['order_id'] . " and goods_id=" . $goods['goods_id'] . " and spec_id=" . $goods['spec_id'], 'fields' => 'status'));


            if ($goods['status'] != 'SUCCESS' && (!$goods_refund || $goods_refund['status'] == 'CLOSED')) {

                $goods_fee = $adjust_rate >= 0 ? $goods['price'] * $goods['quantity'] * $adjust_rate : $order_info['goods_amount'] / count($ordergoods);


                if ($order_info['goods_amount'] > 0) {
                    $goods_shipping_fee = round(($order_info['order_amount'] - $order_info['goods_amount']) * $goods_fee / $order_info['goods_amount'], 2);
                }
                else
                    $goods_shipping_fee = round(($order_info['order_amount'] - $order_info['goods_amount']) / count($ordergoods), 2);

                $shipping_fee += $goods_shipping_fee;

                $goods_amount += $goods_fee;


                $goods_close_refund_and_no_refund[$key] = $goods + array('refund_closed' => $goods_refund ? 1 : 0);
            }
        }

        return array('confirm_ordergoods' => $goods_close_refund_and_no_refund, 'confirm_order_amount' => round($goods_amount, 2) + $shipping_fee);
    }


    private function _check_post_data($refund = array())
    {
        $refund_goods_fee = I('post.refund_goods_fee');
        if (empty($refund_goods_fee) || floatval($refund_goods_fee) < 0) {
            render('19999', '退款金额不能为空且必须大于0');
        } elseif (floatval($refund_goods_fee) > $refund['goods_fee']) {
            render('19999', '退款金额不能小于0或者大于商品总额');
        }
        $refund_shipping_fee = I('post.refund_shipping_fee');
        if ($refund_shipping_fee != '' && floatval($refund_shipping_fee) < 0) {
            render('19999', '退运费金额不能小于0');
        }
        if (floatval($refund_shipping_fee) > $refund['shipping_fee']) {
            render('19999', '退运费金额不能大于该商品分摊的运费金额');
        }
        $refund_reason = I('post.refund_reason');
        if (empty($refund_reason)) {
            render('19999', 'select_refund_reason');
        }
    }

    //对三方支付进行退款封装
    function refundSign($data){

        ini_set('display_errors','on');
        error_reporting(E_ALL);

        $out_trade_no = $data["order_sn"];
        $total_fee = $data["total_fee"] * 100;
        $refund_fee = $data["total_fee"] * 100;
        $refund_alifee = $data["total_fee"];
        if($data['payment_code'] == 'epaywxnative' || $data['payment_code'] == 'wxpay_app' || $data['payment_code'] == 'jspay_app'){
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Data.php";
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Api.php";
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Config.php";
            $input = new WxPayRefund();
            $input->SetOut_trade_no($out_trade_no);
            $input->SetTotal_fee($total_fee);
            $input->SetRefund_fee($refund_fee);
            $config = new WxPay1Config();
            $input->SetOut_refund_no($data['refund_sn']);
            $rs = WxPay1Api::refund($config,$input, 60);
            return $rs;
        }else if($data['payment_code'] == 'epayalipay' || $data['payment_code'] == 'alipay_app'){

            include_once ROOT_PATH."/includes/payments/alipay/aop/AopCertClient.php";
            include_once ROOT_PATH."/includes/payments/alipay/aop/request/AlipayTradeRefundRequest.php";
            $appCertPath    = ALI_APP_CERT_PATH;
            $alipayCertPath = ALI_ALI_PAY_CERT_PATH;
            $rootCertPath   = ALI_ROOT_CERT_PATH;

            $aop = new AopCertClient();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = ALI_APP_ID;
            $aop->rsaPrivateKey = ALI_RSA_PRIVATE_KEY;
            $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='UTF-8';
            $aop->format='json';
            $aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
            $aop->appCertSN = $aop->getCertSN($appCertPath);//调用getCertSN获取证书序列号
            $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);//调用getRootCertSN获取支付宝根证书序列号
            $request = new AlipayTradeRefundRequest();

            //商户订单号，商户网站订单系统中唯一订单号
            $out_trade_no = trim($out_trade_no);
            //需要退款的金额，该金额不能大于订单金额，必填
            $refund_amount = trim($refund_alifee);

            $request->setBizContent("{" .
                "\"out_trade_no\":\"$out_trade_no\"," .
                "\"trade_no\":\"\"," .
                "\"refund_amount\":\"$refund_amount\"," .
                "\"refund_reason\":\"正常退款\"" .
                "  }");
            $result = $aop->execute($request);
            $rs = json_decode(json_encode($result),true);
            return $rs;
        }
    }
}

?>